//
//  XYClassifyController.swift
//  XYReadBook
//
//  Created by fox on 2017/9/5.
//  Copyright © 2017年 tsaievan. All rights reserved.
//

import UIKit

/// TODO 自定义cell
class XYClassifyController: XYViewController {
    
    /// 一级分类
    var classfy:XYClassfy? {
        didSet {
             self.collectionView.reloadData()
        }
    }
    
    /// 二级分类
    var catslv:XYClassfyCatslv?
    
    let Identifier = "ClassifyIdentifier"
   private lazy var  collectionView:UICollectionView =  {
    
        let Layout = UICollectionViewFlowLayout()
        let collectionView = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: Layout)
        Layout.scrollDirection = UICollectionViewScrollDirection.vertical
        Layout.itemSize = CGSize.init(width: ((ScreenWidth - 50) / 3), height: 60)
        //垂直方向间距
        Layout.minimumInteritemSpacing = 0
        Layout.minimumLineSpacing = 10
        Layout.headerReferenceSize = CGSize.init(width: 375, height: 40)

        //水平方向间距
        //设置四周得边缘距离
        Layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(XYClassfyCell.self, forCellWithReuseIdentifier: self.Identifier)
    
        collectionView.register(XYClassifyReusableView.self, forSupplementaryViewOfKind:UICollectionElementKindSectionHeader, withReuseIdentifier: "UICollectionElementKindSectionHeader")
    
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.backgroundColor = UIColor.white
        collectionView.bounces = false
    
        return collectionView
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        loadData()
        setupUI()
        loadCatslvData()
    }

    
    /// 请求数据,并且返回模型,就是那么简单,都不需要转模型 加载一级界面
    func loadData() {
        let url = XYAPI.baseurlFormat(baseURL: BaseUrl.defult.rawValue, key: "cats/lv2/statistics")
        HTTPManager.requestModel(url: url, method: .get, parameters: nil, iscaChe: true) { (resp:XYClassfy?, error) in
            if let resp = resp {
              self.classfy = resp
                XYLog(messsage: "成功")
            }else {
                if error != nil {
                    XYLog(messsage: error)
                }
            }
        }
    }
    
    /// 加载二级界面
    func loadCatslvData() {
        let url = XYAPI.baseurlFormat(baseURL: BaseUrl.defult.rawValue, key: "cats/lv2")
        HTTPManager.requestModel(url: url, method: .get, parameters: nil, iscaChe: true) { (resp:XYClassfyCatslv?, error) in
            if let resp = resp {
              self.catslv = resp
            }
            
            if error != nil {
                XYLog(messsage: error)
            }
        }
    }
    
    
    
    
    func setupUI() {
        view.addSubview(collectionView)
        let item = UIBarButtonItem(title: "返回", style: .plain, target: self, action: nil)
        navigationItem.backBarButtonItem = item
    }
    
    
    
    /// 此方法可以拿到正确的frame等价于layousubView,当界面重新布局
    /// layoutIfNeeded 调用这个方法会标记,下次调用layoutsubviews会加进来
    /// setNeedsLayout 会重新走这个方法 强制布局
    override func viewDidLayoutSubviews() {
        collectionView.frame = CGRect.init(x: 10, y:0, width: ScreenWidth - 20, height: ScreenHeight)
    }

}


// MARK: - 实际项目中最好不要写感叹号! 万一没值就崩溃了
extension XYClassifyController:UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        switch section {
        case 0:
            return classfy?.male.count ?? 0
        case 1:
             return classfy?.female.count ?? 0
        case 2:
            return  classfy?.picture.count ?? 0
        case 3:
            return  classfy?.press.count ?? 0

        default:
            break
            
        }
      return 0
    }
    
    
    
    func  numberOfSections(in collectionView: UICollectionView) -> Int
    {
        
        return 4
    }
    
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell:XYClassfyCell = collectionView.dequeueReusableCell(withReuseIdentifier:Identifier, for: indexPath) as! XYClassfyCell
        cell.backgroundColor = UIColor.hm_color(withRed: 242, green: 242, blue: 242)
        
        switch indexPath.section {
        case 0:
             cell.model = classfy?.male[indexPath.row]
            break
        case 1:
             cell.model = classfy?.female[indexPath.row]
            break
        case 2:
             cell.model = classfy?.picture[indexPath.row]
            break
        case 3:
            cell.model = classfy?.press[indexPath.row]
            break
        default:
            break
        }
        return cell
    }
    
}

extension XYClassifyController:UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        var name = ""
        var model:MajorGeneral?
        var gender = ""
        
        
        switch indexPath.section {
        case 0:
            model = catslv?.male[indexPath.row]
            gender = "male"
            name = classfy?.male[indexPath.row].name ?? ""
            break
        case 1:
            model = catslv?.female[indexPath.row]
            name = classfy?.female[indexPath.row].name ?? ""
            gender = "female"
            break
        case 2:
            
            model = catslv?.picture[indexPath.row]
            name = classfy?.picture[indexPath.row].name ?? ""
            gender = "picture"
            break
        case 3:
            model = catslv?.press[indexPath.row]
            name = classfy?.press[indexPath.row].name ?? ""
            gender = "press"
            break
        default:
            break
        }
        let vc = XYClassfySelectController.init(name: name, gender: gender, model: model!)
        vc.hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(vc, animated: true)
        
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        let reusableview = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "UICollectionElementKindSectionHeader", for: indexPath) as! XYClassifyReusableView
        
        var titleString = ""
        switch indexPath.section {
        case 0: //如果你不写 break 编译器会自动加一个break
            titleString = "男生"
        case 1:
            titleString = "女生"
        case 2:
            titleString = "漫画"
        case 3:
            titleString = "文学"
        default:
            break
        }
        reusableview.titleString = titleString
        
        return reusableview
    }
    
}
